package com.kaifamiao.message;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class MessageDao {
    public static Connection getConnection() {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/messagebook?useSSL=false&characterEncoding=utf8", "root",
                    "123456");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    public static int totalPages(int pageSize) {
        int total = getTotal();
        int totalPages = (total % pageSize == 0) ? (total / pageSize) : (total / pageSize) + 1;
        return totalPages;
    }

    private static int getTotal() {
        try {
            Connection con = getConnection();
            PreparedStatement ps = con.prepareStatement("SELECT COUNT(1) AS total FROM messagebooks");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                return rs.getInt("total");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static List<Message> getRecords(int currentPage, int pageSize) {
        List<Message> list = new ArrayList<Message>();
        int start = 0;
        if (currentPage > 0) {
            start = (currentPage - 1) * pageSize;
        }

        try {
            Connection con = getConnection();
            String sql = "SELECT * FROM messagebooks ORDER BY create_time desc LIMIT " + start + "," + pageSize;
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Message e = new Message();
                e.setId(rs.getInt(1));
                e.setUser(rs.getString(2));
                e.setTitle(rs.getString(3));
                e.setContext(rs.getString(4));
                e.setCreatetime(rs.getString(5));
                list.add(e);
            }
            con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}